package com.springboot.frame.comm.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 代码生成相关工具类
 *
 * @author madman
 */
public class CodeUtils {

  private static final String UNDERLINE = "_";
  private static final Pattern PATTERN = Pattern.compile("[A-Z]");

  private CodeUtils() {
  }

  /**
   * 下划线转大写
   *
   * @param originStr 名称
   * @return 下划线转大写后字符串
   */
  public static String underlineToCamel(String originStr) {
    if (StringUtils.isNotBlank(originStr)) {
      StringBuilder result = new StringBuilder();
      for (String camel : originStr.split(UNDERLINE)) {
        if (StringUtils.isEmpty(camel)) {
          continue;
        }
        if (result.length() == 0) {
          result.append(camel);
        } else {
          result.append(StringUtils.capitalize(camel));
        }
      }
      return result.toString();
    }
    return originStr;
  }

  /**
   * 大写转下划线
   * @param originStr
   * @return
   */
  public static String camelToUnderline(String originStr) {
    if (StringUtils.isNotBlank(originStr)) {
      Matcher mc = PATTERN.matcher(originStr);
      int i = 0;
      StringBuilder sb = new StringBuilder(originStr);
      while (mc.find()) {
        sb.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
        i++;
      }
      if (UNDERLINE.equals(sb.charAt(0))) {
        sb.deleteCharAt(0);
      }
      return sb.toString();
    }
    return originStr;
  }


  /**
   * 去掉指定的前缀
   *
   * @param originStr 名称
   * @param prefix 前缀
   * @return 去掉前缀后字符串
   */
  public static String removePrefix(String originStr, String[] prefix) {
    if (StringUtils.isNotBlank(originStr) && ArrayUtils.isNotEmpty(prefix)) {
      for (String pf : prefix) {
        if (originStr.toLowerCase().matches("^" + pf.toLowerCase() + ".*")) {
          return originStr.substring(pf.length());
        }
      }
    }
    return originStr;
  }

  /**
   * 去掉下划线前缀且将后半部分转成驼峰格式
   *
   * @param originStr 名称
   * @param tablePrefix 前缀
   * @return 去掉下划线前缀且将后半部分转成驼峰格式后的字符串
   */
  public static String removePrefixAndCamel(String originStr, String[] tablePrefix) {
    return underlineToCamel(removePrefix(originStr, tablePrefix));
  }

}
